package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * 短信发送控制器
 */
@Slf4j
@RestController
@RequestMapping("/mobile/validateCode")
public class MobileValidateCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/send")
    public Result sendPhone(User user, HttpSession session) {
        log.info("[预约请求的手机号]：{}", user.getTelephone());
        //获取手机号
        String phone = user.getTelephone();
        //生成随机的4位验证码
        String code = ValidateCodeUtils.generateValidateCode(6).toString();
        log.info("生成的预约手机验证码 = {}", code);

        //TODO 调用阿里云提供的短信服务API完成发送短信
/*        SMSUtils.sendMessage(
                "传智健康项目基手机号登录",
                "SMS_175532136",
                user.getTelephone(),
                code
        );*/

        //需要将生成的验证码保存到Session，作为提交预约的验证
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        session.setAttribute(phone, code);
        return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
    }
}